package cn.tedu.confirm;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

public class OneConfirm {
    public static void main(String[] args) throws Exception{
        //1.配置连接信息
        ConnectionFactory cf = new ConnectionFactory();
        cf.setHost("127.0.0.1");
        cf.setPort(5672);//5672是默认端口，可以省略
        cf.setUsername("guest");
        cf.setPassword("guest");
        //2.创建tcp连接对象
        Connection nc = cf.newConnection();
        //3.创建channel
        Channel cc = nc.createChannel();
        //4.创建一个随机队列
        String queueName = cc.queueDeclare().getQueue();
        //5.开启发布确认
        cc.confirmSelect();
        long start = System.currentTimeMillis();
        for (int i = 0; i < 1000; i++) {
            String msg = "消息："+i;
            cc.basicPublish("",queueName,null,msg.getBytes());
            //阻塞线程等待服务器数据返回响应，用于确认消息是否发送成功
            //如果服务器确认已经发送完成，返回true，否则返回false
            boolean flag = cc.waitForConfirms();
            if (flag){
                System.out.println(msg+"发送成功");
            }
        }
        long end = System.currentTimeMillis();
        System.out.println("发送1000条消息数据使用的时间："+(end-start));
    }
}
